package org.sxf.app.sign.handler;

import android.app.Activity;
import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;

import com.lidroid.xutils.util.LogUtils;

import org.sxf.app.sign.utils.Utility;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;


public class APPHandler {
    private ArrayList<Activity> activityList = new ArrayList<>();
    private static APPHandler instance;
    private Activity mCurrentActivity;

    public Handler getmHandler() {
        return mHandler;
    }

    public void setmHandler(Handler mHandler) {
        this.mHandler = mHandler;
    }

    private Handler mHandler = null;

    private APPHandler() {
    }

    public static APPHandler getInstance() {
        if (instance == null) {
            instance = new APPHandler();
        }
        return instance;
    }

    public void addActivity(Activity activity) {
        activityList.add(activity);
    }

    public void removeActivity(Activity activity){
        activityList.remove(activity);
    }

    public void exit() {

        try {
            clearAllActivity();
        }catch (Exception e){

        }

        System.exit(0);
    }

    public void clearAllActivity(){
        LogUtils.d("activity list size:" + activityList.size());
        for (int i = 0; i < activityList.size(); i++) {
            Activity activity = (Activity) activityList.get(i);
            activity.finish();
        }
        activityList.clear();
    }


    public void setCurrentActivity(Activity currentActivity) {
        LogUtils.d("currentActivity:" + currentActivity.getLocalClassName());
        this.mCurrentActivity = currentActivity;
    }

    public Activity getCurrentActivity(){
        return mCurrentActivity;
    }

    public void clearAllBackgroundActivity(){
        try {
            Iterator<Activity> iterator = activityList.iterator();
            while(iterator.hasNext()){
                Activity activity = iterator.next();
                if(activity != mCurrentActivity){
                    activity.finish();
                    iterator.remove();
                }
            }
        }catch (Exception e){
            LogUtils.e(Utility.getStackTrace(e));
        }

    }
}